package com.sduept.nwld.dataserver.rest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sduept.bigdata.fault.entity.FaultRecord;
import com.sduept.bigdata.fault.entity.FaultReportBreaker;
import com.sduept.bigdata.fault.entity.FaultReportMain;
import com.sduept.bigdata.fault.entity.FaultReportMainProtection;
import com.sduept.bigdata.fault.entity.FaultReportStationDetail;
import com.sduept.bigdata.fault.manager.FaultRecordPersistManager;
import com.sduept.bigdata.fault.protection.model.ProtectChannelAlarm;
import com.sduept.bigdata.fault.protection.service.ProtectChannelAlarmPersistManager;
import com.sduept.bigdata.weather.map.MapDataCache;
import com.sduept.cim.exception.PersistentException;
import com.sduept.cim.model.core.Substation;
import com.sduept.cim.model.protection.ProtectionEquipment;
import com.sduept.cim.model.wires.Breaker;
import com.sduept.cim.parse.CimModelFileParseService;
import com.sduept.cim.parse.exception.ParseException;
import com.sduept.cim.persist.service.CimFullPersistentMapModel;
import com.sduept.cim.persist.service.CimIncrementPersistentListModel;
import com.sduept.cim.persist.service.impl.CimPersistManager;
import com.sduept.cim.query.service.impl.BreakerRelation;
import com.sduept.core.dao.SuperDAO;
import com.sduept.generator.ObjectId;
import com.sduept.nwld.dataserver.manager.cim.CimManager;
import com.sduept.nwld.dataserver.manager.countanalyse.StatisticalAnalysisSchedule;

/**
 * 页面数据测试，在此类内可以添加任何测试方法 适用于无后台的情况
 */
@RestController
@RequestMapping("/test")
public class TestRestService {

	@Autowired
	private SuperDAO dao;
	@Autowired
	private FaultRecordPersistManager fpm;
	@Autowired
	private CimManager cm;

	@Autowired
	private MapDataCache cache;

	@Autowired
	private ProtectChannelAlarmPersistManager protectChannelAlarmPersistManager;

	@Autowired
	private StatisticalAnalysisSchedule statisticalAnalysisSchedule;
	
	@Autowired
	private CimPersistManager CimPersistManager;
	@Autowired
	private CimModelFileParseService cimModelFileParseService;
	
	@Autowired
	private BreakerRelation breakerRelation;
	@GetMapping("/testInitCim")
	public String test1() {
		try {
			if(dao.findAll(Substation.class).size() > 0) {
				return "当前库中有数据，无法init";
			}
			CimFullPersistentMapModel models = cimModelFileParseService.getFullDatas("E:\\公司文档\\部门文档\\项目管理\\南网大数据\\后期维护\\数据\\EMS\\pas_cim_20200520185900.xml.gz");
			CimPersistManager.init(models);
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (PersistentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "ok";
	}
	@GetMapping("/testUpdateCim")
	public String test2() {
		try {
			CimIncrementPersistentListModel models = cimModelFileParseService.getIncrementDatas("E:\\公司文档\\部门文档\\项目管理\\南网大数据\\后期维护\\数据\\cim\\pas_cim_20200616110510.xml.gz");
			CimPersistManager.batchCreate(models.creates);
			CimPersistManager.batchDelete(models.deletes);
			CimPersistManager.batchUpdate(models.updates);
			return "ok";
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (PersistentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "ok";
	}
	@GetMapping("/test2")
	public String generateFaultRecordWrappers() {
		List<FaultRecordWrapper> fs = new ArrayList<>();
		for(FaultRecordWrapper f:fs) {
			fpm.saveFaultRecordOnly(f.fr);
			FaultReportMain m = new FaultReportMain();
			m.setFaultRecord(f.fr);
			//最后2个参数,第一个传入，保护第一次动，第二个传入断路器第一次动
			FaultReportStationDetail fsd1 = getFaultReportStationDetail(f.fr.getStationId(),f.fr.getStationName(),f.fr.getEquipment_id(),f.fr.getFaultType(),f.fr.getFaultPhase(),f.stationPro1,f.stationBrea1);
			FaultReportStationDetail fsd2 = getFaultReportStationDetail(f.fr.getStationId2(),f.fr.getStationName2(),f.fr.getEquipment_id(),f.fr.getFaultType(),f.fr.getFaultPhase(),f.stationPro1,f.stationBrea1);
			fsd1.setFaultReportMain(m);
			fsd2.setFaultReportMain(m);
			m.getFaultReportStationDetails().add(fsd1);
			m.getFaultReportStationDetails().add(fsd2);
			dao.createOrUpdate(m, FaultReportMain.class);
		}
		return "ok";
	}

	@GetMapping("/testStatisticalAnalysisSchedule/{type}")
	public String teststatisticalAnalysisSchedule(@PathVariable("type") int type) throws IOException {
		switch (type) {
			case 1:
				statisticalAnalysisSchedule.executeBusbarInfoCount();
				break;
			case 2:
				statisticalAnalysisSchedule.executeElectricityInfoCount();
				break;
			case 3:
				statisticalAnalysisSchedule.executeFaultFastRemoveCount();
				break;
			case 4:
				statisticalAnalysisSchedule.executePrimaryDeviceCount();
				break;
			case 5:
				statisticalAnalysisSchedule.executeProtectCorrectActCount();
				break;
			case 6:
				statisticalAnalysisSchedule.executeProtectDeviceCount();
				break;
			case 7:
				statisticalAnalysisSchedule.executeTransmissionInfoCount();
				break;

			default:
				break;
		}
		return "OK";
	}

	@GetMapping("/testProtectChannelUpdate/{startId}/{endId}")
	public String testProtectChannelUpdate(@PathVariable("startId") String startId,@PathVariable("endId") String endId) throws IOException {
		String rtn = "输入参数：startId="+startId+" endId="+endId;
		long t1 = System.currentTimeMillis();
		protectChannelAlarmPersistManager.generateUncompletedProtectCommunicationAlarm(startId, endId);
		int t2 = (int) ((System.currentTimeMillis()-t1)/1000);
		rtn += " 执行时间："+t2;
		return "OK !"+rtn;
	}
	@GetMapping("/testBreaker/{id}")
	public String testBreaker(@PathVariable("id") String id
			) throws IOException {
		StringBuilder sb = new StringBuilder();
		try {
			Set<String> sets = breakerRelation.getBreakerById(id);
			for(String s : sets) {
				Breaker b = dao.findById(s, Breaker.class);
				sb.append(s+" "+b.getSubName()+" "+b.getName()+" "+b.getStandVoltagelevel());
				sb.append("</br>");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "OK !</br>"+sb.toString();
	}

	private void setProtectChannelAlarmStationInfo(ProtectChannelAlarm alarm){
		//广西烽火传输网/南宁地区_南宁,01盘2端口  			str格式
		String alarm_object = alarm.getAlarmObject();
		if(alarm_object.split(",")[0].split("/").length>1){
			alarm_object = alarm_object.split(",")[0].split("/")[1];//南宁地区_南宁
			Substation result = bestMatch(alarm_object);
			if(result!=null){
				alarm.setStationId(result.getId());
				alarm.setStationName(result.getName());
				alarm.setVoltage((int)result.getStandVoltagelevel()+"");
			}else{
				alarm.setStationId(null);
				alarm.setStationName(null);
			}
		}
	}
	private Substation bestMatch(String str){
		Collection<Substation> cols = cache.getStationid_map().values();
		for(Substation s :cols){
			if(StringUtils.isEmpty(s.getName())){
				continue;
			}
			String sname = s.getName().toLowerCase().replaceAll("[a-z]*", "");
			if(str.contains(sname) || str.replace("变","站").contains(sname)
					|| str.replace("站","变").contains(sname) || str.replace("变","变电站").contains(sname)
					|| str.replace("变","变电站").contains(sname))
				return s;

			sname = sname.replaceAll("换流","").replaceAll("变电站", "").replaceAll("变", "").replaceAll("站", "");
			if(str.contains(sname) || str.replace("变","站").contains(sname)
					|| str.replace("站","变").contains(sname) || str.replace("变","变电站").contains(sname)
					|| str.replace("变","变电站").contains(sname))
				return s;

			if(sname.contains(str)){
				return s;
			}

		}
		return null;
	}

	class FaultRecordWrapper{
		FaultRecord fr ;
		int stationPro1;
		int stationBrea1;
		int stationPro2;
		int stationBrea2;
	}
	private FaultReportStationDetail getFaultReportStationDetail(String sid,String sname,String eid,String faultType,String phase,int proActionTime1,int breActionTime1) {
		FaultReportStationDetail fsd = new FaultReportStationDetail();
		fsd.setId(ObjectId.get().toString());
		fsd.setStationId(sid);
		fsd.setStationName(sname);
		List<ProtectionEquipment> pros = cm.listMainEquipmentsByStationIdAndprotectedId(sid,eid);
		for(ProtectionEquipment pe:pros) {
			List<FaultReportMainProtection> fps = getFaultReportMainProtection(pe, faultType, phase, proActionTime1);
			for(FaultReportMainProtection fp:fps) {
				fp.setFaultReportStationDetail(fsd);
				fsd.getFaultReportMainProtectionActions().add(fp);
			}
		}
		//断路器
		List<Breaker> breaks = cm.getBreakersById(eid, sid);
		for(Breaker br:breaks) {
			List<FaultReportBreaker> fps = getFaultReportBreaker(br, faultType, phase, breActionTime1);
			for(FaultReportBreaker fp:fps) {
				fp.setFaultReportStationDetail(fsd);
				fsd.getFaultReportBreakerActions().add(fp);
			}
		}
		return fsd;
	}
	//设置保护动作信息
	private List<FaultReportMainProtection> getFaultReportMainProtection(ProtectionEquipment pe,String faultType,String faultPhase,int actionTime1/*,int actionTime2*/) {
		List<FaultReportMainProtection> list = new ArrayList<FaultReportMainProtection>();
		if(faultPhase.length()==1 && "单瞬".equals(faultType)) {
			FaultReportMainProtection fm1 = new FaultReportMainProtection();
			fm1.setId(ObjectId.get().toString());
			fm1.setDistance0MomentsTime(actionTime1);
			fm1.setPhase(faultPhase);
			fm1.setProtectionId(pe.getId());
			fm1.setProtectionName(pe.getType());
			fm1.setActionType("trip");
			list.add(fm1);
		}else if(faultPhase.length()==1 && "单永".equals(faultType)) {
			FaultReportMainProtection fm1 = new FaultReportMainProtection();
			fm1.setId(ObjectId.get().toString());
			fm1.setDistance0MomentsTime(actionTime1);
			fm1.setPhase(faultPhase);
			fm1.setProtectionId(pe.getId());
			fm1.setProtectionName(pe.getType());
			fm1.setActionType("trip");
			list.add(fm1);
			/*
			 * String[] phases = {"A","B","C"}; for(String phase:phases) {
			 * FaultReportMainProtection fm2 = new FaultReportMainProtection();
			 * fm2.setId(ObjectId.get().toString());
			 * fm2.setDistance0MomentsTime(actionTime2); fm2.setPhase(phase);
			 * fm2.setProtectionId(pe.getId()); fm2.setProtectionName(pe.getType());
			 * fm2.setActionType("threeTrip"); list.add(fm2); }
			 */
		}else if(faultPhase.length()>1) {
			String[] phases = {"A","B","C"};
			for(String phase:phases) {
				FaultReportMainProtection fm1 = new FaultReportMainProtection();
				fm1.setId(ObjectId.get().toString());
				fm1.setDistance0MomentsTime(actionTime1);
				fm1.setPhase(phase);
				fm1.setProtectionId(pe.getId());
				fm1.setProtectionName(pe.getType());
				fm1.setActionType("trip");
				list.add(fm1);
			}
		}
		return list;
	}
	//设置断路器动作信息
	private List<FaultReportBreaker> getFaultReportBreaker(Breaker br,String faultType,String faultPhase,int actionTime1/*,int actionTime2*/) {
		List<FaultReportBreaker> list = new ArrayList<FaultReportBreaker>();
		if(faultPhase.length()==1 && "单瞬".equals(faultType)) {
			FaultReportBreaker fm1 = new FaultReportBreaker();
			fm1.setId(ObjectId.get().toString());
			fm1.setDistance0MomentsTime(actionTime1);
			fm1.setPhase(faultPhase);
			fm1.setBreakerId(br.getId());
			fm1.setBreakerName(br.getName());
			fm1.setActionType("trip");
			list.add(fm1);
		}else if(faultPhase.length()==1 && "单永".equals(faultType)) {
			FaultReportBreaker fm1 = new FaultReportBreaker();
			fm1.setId(ObjectId.get().toString());
			fm1.setDistance0MomentsTime(actionTime1);
			fm1.setPhase(faultPhase);
			fm1.setBreakerId(br.getId());
			fm1.setBreakerName(br.getName());
			fm1.setActionType("trip");
			list.add(fm1);
			/*
			 * String[] phases = {"A","B","C"}; for(String phase:phases) {
			 * FaultReportMainProtection fm2 = new FaultReportMainProtection();
			 * fm2.setId(ObjectId.get().toString());
			 * fm2.setDistance0MomentsTime(actionTime2); fm2.setPhase(phase);
			 * fm2.setProtectionId(pe.getId()); fm2.setProtectionName(pe.getType());
			 * fm2.setActionType("threeTrip"); list.add(fm2); }
			 */
		}else if(faultPhase.length()>1) {
			String[] phases = {"A","B","C"};
			for(String phase:phases) {
				FaultReportBreaker fm1 = new FaultReportBreaker();
				fm1.setId(ObjectId.get().toString());
				fm1.setDistance0MomentsTime(actionTime1);
				fm1.setPhase(phase);
				fm1.setBreakerId(br.getId());
				fm1.setBreakerName(br.getName());
				fm1.setActionType("trip");
				list.add(fm1);
			}
		}
		return null;
	}

	/*
	 * public static String[] areas = new String[] { "超高压公司", "调峰调频公司", "广东电网",
	 * "广州电网", "深圳电网", "广西电网", "云南电网", "贵州电网", "海南电网" };
	 *
	 * @GET
	 *
	 * @Path("/test1")
	 *
	 * @Produces(MediaType.APPLICATION_JSON) public String getStations() {
	 * JSONObject rtn = new JSONObject(); rtn.put("param3", areas); return
	 * rtn.toJSONString(); }
	 *
	 * @GET
	 *
	 * @Path("/test2")
	 *
	 * @Produces(MediaType.APPLICATION_JSON) public String getStations2() {
	 * JSONObject rtn = new JSONObject(); rtn.put("prop.WAVE_FILE_PATH",
	 * prop.getWAVE_FILE_PATH()); return rtn.toJSONString(); }
	 */
}
